package org.hepeng.workx.spring.cloud.netflix.zuul.route;

import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.spring.context.ApplicationContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.tuckey.web.filters.urlrewrite.extend.RewriteMatch;
import org.tuckey.web.filters.urlrewrite.extend.RewriteRule;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Objects;

/**
 * @author he peng
 */
public abstract class AbstractZuulRoutingUrlRewriteRule extends RewriteRule {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractZuulRoutingRewriteMatch.class);

    private RouteLocator routeLocator;

    @Override
    public RewriteMatch matches(HttpServletRequest request , HttpServletResponse response) {
        String queryString = request.getQueryString();
        String originalUri = request.getRequestURI();
        if (StringUtils.isNotBlank(queryString)) {
            originalUri += "?" + queryString;
        }
        if (Objects.isNull(this.routeLocator)) {
            this.routeLocator = ApplicationContextHolder
                    .getApplicationContext()
                    .getBean(RouteLocator.class);
        }

        return newRewriteMatch(request , originalUri , this.routeLocator.getRoutes());
    }

    protected abstract RewriteMatch newRewriteMatch(HttpServletRequest request , String originalUri, List<Route> routes);
}
